package com.bps.ksiazkaadresowa;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;

import javax.swing.table.AbstractTableModel;

public class KAModel extends AbstractTableModel {
	private static final long serialVersionUID = 1L;
	private Vector<Osoba> data;
	private String[] colNames = {
			"L.p.",
			"Nazwisko",
			"Imię",
			"Kod pocztowy",
			"Miasto",
			"Ulica",
			"Telefon",
			"Telefon 2"};
	
	public KAModel() {
		super();
		data = new Vector<Osoba>();
	}
	
	@Override
	public int getColumnCount() {
		return colNames.length;
	}

	@Override
	public String getColumnName(int column) {
		return colNames[column];
	}
	
	@Override
	public int getRowCount() {
		return data.size();
	}

	@Override
	public Object getValueAt(int row, int col) {
		Osoba osoba = data.get(row);
		switch (col) {
		case 0:
			return row;
		case 1:
			return osoba.getNazwisko();
		case 2:
			return osoba.getImie();
		case 3:
			return osoba.getKodPocztowy();
		case 4:
			return osoba.getMiasto();
		case 5:
			return osoba.getUlica();
		case 6:
			return osoba.getTelefon();
		case 7:
			return osoba.getTelefon2();

		default:
			break;
		}
		return null;
	}
	
	public void addOsoba(Osoba osoba) {
		data.addElement(osoba);
		int updatedRow = data.indexOf(data.lastElement());
		fireTableRowsInserted(updatedRow, updatedRow);
	}
	
	public void removeOsoba(int index) {
		data.remove(index);
		fireTableRowsDeleted(index, index);
	}
	
	public void updateOsoba(int index, Osoba newOsoba) {
		data.set(index, newOsoba);
		fireTableRowsUpdated(index, index);
	}
	
	public Osoba getOsoba(int index) {
		return data.get(index);
	}
	
	public void saveToFile(File f) {
		try {
			ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(f));
			for (Osoba osoba : data) {
				outputStream.writeObject(osoba);
			}
			outputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void loadFromFile(File f) {
		try {
			ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(f));
			Osoba osoba = null;
			while((osoba = (Osoba) inputStream.readObject()) != null){
				data.addElement(osoba);
			}
			inputStream.close();
			fireTableDataChanged();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (EOFException e) {
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
	}
}
